package com.jia.lidao.others.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.jia.lidao.R;
import com.jia.lidao.RunningContext;
import com.jia.lidao.UserUtils;
import com.jia.lidao.others.API;
import com.jia.lidao.others.BaseFragment;
import com.jia.lidao.others.enity.AddressDetail;
import com.jia.lidao.others.enity.ModelBeen;
import com.jia.lidao.others.enity.ObjectCallBack;
import com.jia.lidao.others.enity.Province;
import com.jia.lidao.others.ui.CityListActivity;
import com.jia.lidao.utils.CommonUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by 00029935 on 2017/12/4.
 */

public class AddNewAddressFragment extends BaseFragment {
    @BindView(R.id.ib_back)
    ImageView ibBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_choice_address)
    LinearLayout llChoiceAddress;
    @BindView(R.id.et_detail_address)
    EditText etDetailAddress;
    @BindView(R.id.cb_default)
    CheckBox cbDefault;
    @BindView(R.id.tv_add_new_address)
    TextView tvAddNewAddress;
    private Province.RegionsBean myProvince;
    private Province.RegionsBean myCity;
    private Province.RegionsBean myArea;
    private int is_default = 0;

    private int id = -1;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        id = getActivity().getIntent().getIntExtra("ID", -1);
    }

    @Override
    protected int getInflateLayout() {
        return R.layout.add_new_address_fragment;
    }

    @Override
    protected void setUpView(View view) {
        if (id != -1) {
            tvTitle.setText("编辑地址");
        } else {
            tvTitle.setText("添加新地址");
        }
        etPhone.setFilters(
                new InputFilter[] { new InputFilter.LengthFilter(11) });
        ibBack.setImageResource(R.mipmap.share_back);

        cbDefault.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                is_default = isChecked ? 1 : 0;
            }
        });

        if (id != -1) {
            queryDetail(id);
        }
        if(id==-1){
            cbDefault.setChecked(true);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick({R.id.ib_back, R.id.ll_choice_address, R.id.tv_add_new_address})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_back:
                getActivity().finish();
                break;
            case R.id.ll_choice_address:
                Intent integer = new Intent(getContext(), CityListActivity.class);
                startActivityForResult(integer, 3);

                break;
            case R.id.tv_add_new_address:
                String consignee = etName.getText().toString().trim();
                if (TextUtils.isEmpty(consignee)) {
                    showToast("请输入收货人姓名");
                    return;
                }

                String phone = etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    showToast("请输入手机号");
                    return;
                }

                String detail = etDetailAddress.getText().toString().trim();
                if (TextUtils.isEmpty(detail)) {
                    showToast("请输入详细地址");
                    return;
                }
                if (null == myProvince) {
                    showToast("请选择地区");
                    return;
                }
                if(!CommonUtil.checkPhone(etPhone.getText().toString())){
                    showToast("请输入正确的手机号");
                    return;
                }

                queryData(consignee, phone, myProvince.getId(), myCity.getId(), myArea.getId(), detail, is_default);
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 3:

                myProvince = (Province.RegionsBean) data.getSerializableExtra("Province");
                myCity = (Province.RegionsBean) data.getSerializableExtra("City");
                myArea = (Province.RegionsBean) data.getSerializableExtra("Area");
                String address = myProvince.getName() + "-" + myCity.getName() + "-" + myArea.getName();
                tvAddress.setText(address);
                break;
        }
    }

    private void queryData(String consignee, String phone, int province_id, int city_id, int county_id, String street, int is_default) {
        String url;
        if (id == -1) {
            url = API.MEMBER_ADDRESS +
                    "consignee=" + consignee +
                    "&phone=" + phone +
                    "&province_id=" + province_id +
                    "&city_id=" + city_id +
                    "&county_id=" + county_id +
                    "&street=" + street +
                    "&is_default=" + is_default +
                    "&access_token=" + UserUtils.getInstance().getAuthor().access_token;
        } else {
            url = API.MEMBER_ADDRESS +
                    "consignee=" + consignee +
                    "&phone=" + phone +
                    "&province_id=" + province_id +
                    "&city_id=" + city_id +
                    "&county_id=" + county_id +
                    "&street=" + street +
                    "&is_default=" + is_default +
                    "&access_token=" + UserUtils.getInstance().getAuthor().access_token + "&id=" + id;
        }


        HashMap<String, String> header = new HashMap<>();
        header.put("Accept", "*/*");

        TypeToken<ModelBeen> typeToken = new TypeToken<ModelBeen>() {
        };
        OkHttpUtils.post().url(url).headers(header).build().execute(new ObjectCallBack<ModelBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ModelBeen response, int id) {
                if (response.err_code == 0) {
                    showToast("保存成功！");
                    getActivity().finish();
                } else {
                    showToast(response.err_msg);
                }
            }
        });
    }

    private void queryDetail(int id) {
        String url = API.MEMBER_ADDRESSES_DEFAULT + id + "?" + "access_token=" + UserUtils.getInstance().getAuthor().access_token;
        HashMap<String, String> header = new HashMap<>();
        header.put("Accept", "*/*");
        TypeToken<AddressDetail> typeToken = new TypeToken<AddressDetail>() {
        };
        OkHttpUtils.get().url(url).headers(header).build().execute(new ObjectCallBack<AddressDetail>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(AddressDetail response, int id) {
                if (null != response) {
                    if (response.getErr_code() == 0) {
                        AddressDetail.AddressBean addressBean = response.getAddress();
                        etName.setText(addressBean.getConsignee());
                        etPhone.setText(addressBean.getPhone());
                        myProvince = new Province.RegionsBean();
                        myProvince.setId(addressBean.getProvince_id());
                        myProvince.setName(addressBean.getProvince_name());
                        myCity = new Province.RegionsBean();
                        myCity.setName(addressBean.getCity_name());
                        myCity.setId(addressBean.getCity_id());
                        myArea = new Province.RegionsBean();
                        myArea.setName(addressBean.getCounty_name());
                        myArea.setId(addressBean.getCounty_id());
                        String address = myProvince.getName() + "-" + myCity.getName() + "-" + myArea.getName();
                        tvAddress.setText(address);

                        etDetailAddress.setText(addressBean.getStreet());

                        int defaul = addressBean.getIs_default();
                        cbDefault.setChecked(defaul == 1 ? true : false);
                    } else {
                        showToast(response.getErr_msg());
                    }
                }

            }
        });
    }
}
